<!DOCTYPE HTML>
<html lang="zh-CN">


<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta name="keywords" content="【Linux】Linux驱动基础, ZhengN_Blog">
    <meta name="description" content="上一篇分享的：从单片机工程师的角度看嵌入式Linux中有简单提到Linux的三大类驱动：

我们学习编程的时候都会从hello程序开始。同样的，学习Linux驱动我们也从最简单的hello驱动学起。
驱动层和应用层还记得实习那会儿我第一次接">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>【Linux】Linux驱动基础 | ZhengN_Blog</title>
    <link rel="icon" type="image/jpeg" href="/favicon.jpg">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <style type="text/css">
        
    </style>

    <script src="/libs/jquery/jquery-2.2.0.min.js"></script>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>

<header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">ZhengN_Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>首页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/tags" class="waves-effect waves-light">
            
            <i class="fa fa-tags"></i>
            
            <span>标签</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/categories" class="waves-effect waves-light">
            
            <i class="fa fa-bookmark"></i>
            
            <span>分类</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/friends" class="waves-effect waves-light">
            
            <i class="fa fa-address-book"></i>
            
            <span>友情链接</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">ZhengN_Blog</div>
        <div class="logo-desc">
            
            printf(&#34;每天进步一点点~&#34;);
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                首页
            </a>
        </li>
        
        <li>
            <a href="/tags" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-tags"></i>
                
                标签
            </a>
        </li>
        
        <li>
            <a href="/categories" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-bookmark"></i>
                
                分类
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于
            </a>
        </li>
        
        <li>
            <a href="/friends" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-address-book"></i>
                
                友情链接
            </a>
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/zhengnianli/stm32_weather" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/zhengnianli/stm32_weather" class="github-corner tooltipped hide-on-med-and-down" target="_blank" data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewbox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/>
    </svg>
</a>
        
    </nav>

</header>





<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/20.jpg')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        【Linux】Linux驱动基础
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 20px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/嵌入式/" target="_blank">
                                <span class="chip bg-color">嵌入式</span>
                            </a>
                        
                            <a href="/tags/Linux/" target="_blank">
                                <span class="chip bg-color">Linux</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Linux/" class="post-category" target="_blank">
                                Linux
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-03-12
                </div>

                
                    
                    <div class="info-break-policy">
                        <i class="fa fa-file-word-o fa-fw"></i>文章字数:&nbsp;&nbsp;
                        3.4k
                    </div>
                    

                    
                    <div class="info-break-policy">
                        <i class="fa fa-clock-o fa-fw"></i>阅读时长:&nbsp;&nbsp;
                        14 分
                    </div>
                    
                
				
				
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="fa fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>上一篇分享的：<a href="https://www.lizhengnian.cn/2020/03/12/cong-dan-pian-ji-gong-cheng-shi-de-jiao-du-kan-qian-ru-shi-linux/">从单片机工程师的角度看嵌入式Linux</a>中有简单提到Linux的三大类驱动：</p>
<p><img src="https://s1.ax1x.com/2020/03/15/83bCNT.png" alt="83bCNT.png"></p>
<p>我们学习编程的时候都会从hello程序开始。同样的，学习Linux驱动我们也从最简单的hello驱动学起。</p>
<h2 id="驱动层和应用层"><a href="#驱动层和应用层" class="headerlink" title="驱动层和应用层"></a>驱动层和应用层</h2><p>还记得实习那会儿我第一次接触嵌入式Linux项目的时候，我的导师让我去学习项目的其它模块，然后尝试着写一个串口相关的应用。那时候知道可以把设备当做文件来操作，但是不知道为什么是这样，就去网上搜了一些代码（驱动代码），然后和我的应用代码放在同一个文件里。</p>
<p>给导师看了之后，导师说那些驱动程序不需要我写，那些驱动已经写好被编译到内核里了，可以直接用了，我只需关注应用层就好了。我当时脑子里就在打转。。what？</p>
<p>STM32用一个串口不就是串口初始化，然后想怎么用就怎么用吗？后来经过学习才知道原来是那么一回事呀。这就是单片机转转嵌入式Linux的思维误区之一。学嵌入式Linux之前我们有必要暂时忘了我们单片机的开发方式，重新梳理嵌入式Linux的开发流程。下面看一下STM32裸机开发与嵌入式Linux开发的一些区别：</p>
<p><img src="https://s1.ax1x.com/2020/03/15/83HzBq.png" alt="83HzBq.png"></p>
<p><img src="https://s1.ax1x.com/2020/03/15/83bP4U.png" alt="83bP4U.png"><br><img src="https://s1.ax1x.com/2020/03/15/83b9EV.png" alt="83b9EV.png"></p>
<p>嵌入式Linux的开发方式与STM32裸机开发的方式有点不一样。在STM32的裸机开发中，驱动层与应用层的区分可能没有那么明显，常常都杂揉在一起。当然，有些很有水平的裸机程序分层分得还是很明显的。</p>
<p>但是，在嵌入式Linux中，驱动和应用的分层是特别明显的，最直观的感受就是驱动程序是一个.c文件里，应用程序是另一个.c文件。比如我们这个hello驱动实验中，我们的驱动程序为hello_drv.c、应用程序为hello_app.c。</p>
<p>驱动模块的加载有两种方式：第一种方式是动态加载的方式，即驱动程序与内核分开编译，在内核运行的过程中加载；第二种方式是静态加载的方式，即驱动程序与内核一同编译，在内核启动过程中加载驱动。在调试驱动阶段常常选用第一种方式，因为较为方便；在调试完成之后才采用第二种方式与内核一同编译。</p>
<p>STM32裸机开发与嵌入式Linux开发还有一点不同的就是：STM32裸机开发最终要烧到板子的常常只有一个文件（除开含有IAP程序的情况或者其它情况），嵌入式Linux就需要分开编译、烧写。</p>
<h2 id="Linux字符设备驱动框架"><a href="#Linux字符设备驱动框架" class="headerlink" title="Linux字符设备驱动框架"></a>Linux字符设备驱动框架</h2><p>我们先看一个图：</p>
<p><img src="https://s1.ax1x.com/2020/03/15/83bSH0.png" alt="83bSH0.png"></p>
<p>当我们的应用在调用open、close、write、read等函数时，为什么就能操控硬件设备。那是因为有驱动层在支撑着与硬件相关的操作，应用程序在调用打开、关闭、读、写等操作会触发相应的驱动层函数。</p>
<p>本篇笔记我们以hello驱动做分享，hello驱动属于字符设备。实现的驱动函数大概是怎么样的是有<code>套路</code>可寻的，这个套路在内核文件<code>include/linux/fs.h</code>中，这个文件中有如下结构体：</p>
<p><img src="https://s1.ax1x.com/2020/03/15/83bFCF.png" alt="83bFCF.png"></p>
<p>这个结构体里的成员都是些函数指针变量，我们需要根据实际的设备确定我们需要创建哪些驱动函数实体。比如我们的hello驱动的几个基本的函数（打开/关闭/读/写）可创建为（以下代码来自：百问网）：</p>
<p><strong>（1）打开操作</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">static</span> <span class="token keyword">int</span> <span class="token function">hello_drv_open</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> inode <span class="token operator">*</span>node<span class="token punctuation">,</span> <span class="token keyword">struct</span> file <span class="token operator">*</span>file<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>打开函数的两个形参的类型要与<code>struct file_operations</code>结构体里<code>open</code>成员的形参类型一致，里面有一句打印语句，方便直观地看到驱动的运行过程。</p>
<p><strong>（2）关闭操作</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">static</span> <span class="token keyword">int</span> <span class="token function">hello_drv_close</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> inode <span class="token operator">*</span>node<span class="token punctuation">,</span> <span class="token keyword">struct</span> file <span class="token operator">*</span>file<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p><strong>（3）读操作</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">static</span> ssize_t <span class="token function">hello_drv_read</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> file <span class="token operator">*</span>file<span class="token punctuation">,</span> <span class="token keyword">char</span> __user <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t size<span class="token punctuation">,</span> loff_t <span class="token operator">*</span>offset<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">int</span> err<span class="token punctuation">;</span>
    <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    err <span class="token operator">=</span> <span class="token function">copy_to_user</span><span class="token punctuation">(</span>buf<span class="token punctuation">,</span> kernel_buf<span class="token punctuation">,</span> <span class="token function">MIN</span><span class="token punctuation">(</span><span class="token number">1024</span><span class="token punctuation">,</span> size<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token function">MIN</span><span class="token punctuation">(</span><span class="token number">1024</span><span class="token punctuation">,</span> size<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p><code>copy_to_user</code>函数的原型为：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">static</span> <span class="token keyword">inline</span> <span class="token keyword">int</span> <span class="token function">copy_to_user</span><span class="token punctuation">(</span><span class="token keyword">void</span> __user <span class="token operator">*</span>to<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">void</span> <span class="token operator">*</span>from<span class="token punctuation">,</span> <span class="token keyword">unsigned</span> <span class="token keyword">long</span> n<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>用该函数来读取内核空间（<code>kernel_buf</code>）的数据给到用户空间（<code>buf</code>）。 另外，kernel_buf的定义如下：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">static</span> <span class="token keyword">char</span> kernel_buf<span class="token punctuation">[</span><span class="token number">1024</span><span class="token punctuation">]</span><span class="token punctuation">;</span></code></pre>
<p>MIN为宏：</p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">define</span> MIN(a, b) (a &lt; b ? a : b)</span></code></pre>
<p>把<code>MIN(1024, size)</code>作为<code>copy_to_user</code>的实参意在对拷贝的数据长度做限制（不能超出kernel_buf的大小）。</p>
<p><strong>（4）写操作</strong></p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">static</span> ssize_t <span class="token function">hello_drv_write</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> file <span class="token operator">*</span>file<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">char</span> __user <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t size<span class="token punctuation">,</span> loff_t <span class="token operator">*</span>offset<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">int</span> err<span class="token punctuation">;</span>
    <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    err <span class="token operator">=</span> <span class="token function">copy_from_user</span><span class="token punctuation">(</span>kernel_buf<span class="token punctuation">,</span> buf<span class="token punctuation">,</span> <span class="token function">MIN</span><span class="token punctuation">(</span><span class="token number">1024</span><span class="token punctuation">,</span> size<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token function">MIN</span><span class="token punctuation">(</span><span class="token number">1024</span><span class="token punctuation">,</span> size<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>copy_from_user函数的原型为：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">static</span> <span class="token keyword">inline</span> <span class="token keyword">int</span> <span class="token function">copy_from_user</span><span class="token punctuation">(</span><span class="token keyword">void</span> <span class="token operator">*</span>to<span class="token punctuation">,</span><span class="token keyword">const</span> <span class="token keyword">void</span> __user <span class="token keyword">volatile</span> <span class="token operator">*</span>from<span class="token punctuation">,</span><span class="token keyword">unsigned</span> <span class="token keyword">long</span> n<span class="token punctuation">)</span></code></pre>
<p>用该函数来将用户空间（<code>buf</code>）的数据传送到内核空间（<code>kernel_buf</code>）。 </p>
<p>有了这些驱动函数，就可以给到一个<code>struct file_operations</code>类型的结构体变量<code>hello_drv</code>，如：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">static</span> <span class="token keyword">struct</span> file_operations hello_drv <span class="token operator">=</span> 
<span class="token punctuation">{</span>
    <span class="token punctuation">.</span>owner   <span class="token operator">=</span> THIS_MODULE<span class="token punctuation">,</span>
    <span class="token punctuation">.</span>open    <span class="token operator">=</span> hello_drv_open<span class="token punctuation">,</span>
    <span class="token punctuation">.</span>read    <span class="token operator">=</span> hello_drv_read<span class="token punctuation">,</span>
    <span class="token punctuation">.</span>write   <span class="token operator">=</span> hello_drv_write<span class="token punctuation">,</span>
    <span class="token punctuation">.</span>release <span class="token operator">=</span> hello_drv_close<span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span></code></pre>
<p>有些朋友可能没见过这种结构体初始化的形式（结构体成员前面加个.号），可以去看往期笔记：[【C语言笔记】结构体]。</p>
<p>上面这个结构体变量<code>hello_drv</code>容纳了我们<code>hello</code>设备的驱动接口，最终我们要把这个<code>hello_drv</code>注册给Linux内核，套路就是这样的：把驱动程序注册给内核，之后我们的应用程序就可以使用<code>open/close/write/read</code>等函数来操控我们的设备，Linux内核在这里起到一个中间人的作用，把两头的驱动与应用协调得很好。</p>
<p>我们前面说了驱动的装载方式之一的动态装载：把驱动程序编译成模块，再动态装载。动态装载的体现就是开发板已经启动运行了Linux内核，我们通过开发板串口终端使用命令来装载驱动。装载驱动有两个命令，比如装载我们的hello驱动：</p>
<pre class=" language-c"><code class="language-c">方法一：insmod hello_drv<span class="token punctuation">.</span>ko
方法二：modprobe hello_drv<span class="token punctuation">.</span>ko</code></pre>
<p>其中<code>modprobe</code>命令不仅能装载当前驱动，而且还会同时装载与当前驱动相关的依赖驱动。有了转载就有卸载，也有两种方式：</p>
<pre class=" language-c"><code class="language-c">方法一：rmmod hello_drv<span class="token punctuation">.</span>ko
方法二：modprobe <span class="token operator">-</span>r hello_drv<span class="token punctuation">.</span>ko</code></pre>
<p>其中<code>modprobe</code>命令不仅卸载当前驱动，也会同时卸载依赖驱动。</p>
<p>我们在串口终端调用装载与卸载驱动的命令，怎么就会执行装载与卸载操作。对应到驱动程序里我们有如下两个函数：</p>
<pre class=" language-c"><code class="language-c"><span class="token function">module_init</span><span class="token punctuation">(</span>hello_init<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">//注册模块加载函数</span>
<span class="token function">module_exit</span><span class="token punctuation">(</span>hello_exit<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">//注册模块卸载函数</span></code></pre>
<p>这里加载与注册有用到<code>hello_init</code>、<code>hello_exit</code>函数，我们前面说的把<code>hello_drv</code>驱动注册到内核就是在<code>hello_init</code>函数里做，如：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">static</span> <span class="token keyword">int</span> __init <span class="token function">hello_init</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">int</span> err<span class="token punctuation">;</span>

    <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">/* 注册hello驱动 */</span>
    major <span class="token operator">=</span> <span class="token function">register_chrdev</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span>               <span class="token comment" spellcheck="true">/* 主设备号,为0则系统自动分配 */</span>
                            <span class="token string">"hello"</span><span class="token punctuation">,</span>       <span class="token comment" spellcheck="true">/* 设备名称 */</span>
                            <span class="token operator">&amp;</span>hello_drv<span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">/* 驱动程序 */</span>

    <span class="token comment" spellcheck="true">/* 下面操作是为了在/dev目录中生成一个hello设备节点 */</span>
    <span class="token comment" spellcheck="true">/* 创建一个类 */</span>
    hello_class <span class="token operator">=</span> <span class="token function">class_create</span><span class="token punctuation">(</span>THIS_MODULE<span class="token punctuation">,</span> <span class="token string">"hello_class"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    err <span class="token operator">=</span> <span class="token function">PTR_ERR</span><span class="token punctuation">(</span>hello_class<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">IS_ERR</span><span class="token punctuation">(</span>hello_class<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">unregister_chrdev</span><span class="token punctuation">(</span>major<span class="token punctuation">,</span> <span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 创建设备，该设备创建在hello_class类下面 */</span>
    <span class="token function">device_create</span><span class="token punctuation">(</span>hello_class<span class="token punctuation">,</span> <span class="token constant">NULL</span><span class="token punctuation">,</span> <span class="token function">MKDEV</span><span class="token punctuation">(</span>major<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token constant">NULL</span><span class="token punctuation">,</span> <span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">/* /dev/hello */</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>这里这个驱动程序入口函数hello_init中注册完驱动程序之后，同时通过下面连个创建操作来创建设备节点，即在/dev目录下生成设备文件。据我了解，在之前版本的Linux内核中，设备节点需要手动创建，即通过创建节点命令mknod 在/dev目录下自己手动创建设备文件。既然已经有新的方式创建节点了，这里就不抠之前的内容了。</p>
<p>以上就是分享关于驱动一些内容，通过以上分析，我们知道，其是有套路（就是常说的驱动框架）可寻的，比如：</p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/module.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/kernel.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/init.h></span></span>
<span class="token comment" spellcheck="true">/* 其她头文件...... */</span>

<span class="token comment" spellcheck="true">/* 一些驱动函数 */</span>
<span class="token keyword">static</span> ssize_t <span class="token function">xxx_read</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> file <span class="token operator">*</span>file<span class="token punctuation">,</span> <span class="token keyword">char</span> __user <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t size<span class="token punctuation">,</span> loff_t <span class="token operator">*</span>offset<span class="token punctuation">)</span>
<span class="token punctuation">{</span>

<span class="token punctuation">}</span>

<span class="token keyword">static</span> ssize_t <span class="token function">xxx_write</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> file <span class="token operator">*</span>file<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">char</span> __user <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t size<span class="token punctuation">,</span> loff_t <span class="token operator">*</span>offset<span class="token punctuation">)</span>
<span class="token punctuation">{</span>

<span class="token punctuation">}</span>

<span class="token keyword">static</span> <span class="token keyword">int</span> <span class="token function">xxx_open</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> inode <span class="token operator">*</span>node<span class="token punctuation">,</span> <span class="token keyword">struct</span> file <span class="token operator">*</span>file<span class="token punctuation">)</span>
<span class="token punctuation">{</span>

<span class="token punctuation">}</span>

<span class="token keyword">static</span> <span class="token keyword">int</span> <span class="token function">xxx_close</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> inode <span class="token operator">*</span>node<span class="token punctuation">,</span> <span class="token keyword">struct</span> file <span class="token operator">*</span>file<span class="token punctuation">)</span>
<span class="token punctuation">{</span>

<span class="token punctuation">}</span>
<span class="token comment" spellcheck="true">/* 其它驱动函数...... */</span>

<span class="token comment" spellcheck="true">/* 定义自己的驱动结构体 */</span>
<span class="token keyword">static</span> <span class="token keyword">struct</span> file_operations xxx_drv <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token punctuation">.</span>owner     <span class="token operator">=</span> THIS_MODULE<span class="token punctuation">,</span>
    <span class="token punctuation">.</span>open    <span class="token operator">=</span> xxx_open<span class="token punctuation">,</span>
    <span class="token punctuation">.</span>read    <span class="token operator">=</span> xxx_read<span class="token punctuation">,</span>
    <span class="token punctuation">.</span>write   <span class="token operator">=</span> xxx_write<span class="token punctuation">,</span>
    <span class="token punctuation">.</span>release <span class="token operator">=</span> xxx_close<span class="token punctuation">,</span>
    <span class="token comment" spellcheck="true">/* 其它程序......... */</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/* 驱动入口函数 */</span>
<span class="token keyword">static</span> <span class="token keyword">int</span> __init <span class="token function">xxx_init</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>

<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">/* 驱动出口函数 */</span>
<span class="token keyword">static</span> <span class="token keyword">void</span> __exit <span class="token function">hello_exit</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>

<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">/* 模块注册与卸载函数 */</span>
<span class="token function">module_init</span><span class="token punctuation">(</span>xxx_init<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">module_exit</span><span class="token punctuation">(</span>xxx_exit<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/* 模块许可证（必选项） */</span>
<span class="token function">MODULE_LICENSE</span><span class="token punctuation">(</span><span class="token string">"GPL"</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>按照这样的套路来开发驱动程序的，有套路可寻那就比较好学习了，至少不会想着怎么起函数名而烦恼，按套路来就好，哈哈</p>
<p>关于驱动的知识，这篇笔记中还可以展开很多内容，限于篇幅就不展开了。我们之后再进行学习、分享。下面看一下测试程序/应用程序（hello_drv_test.c中的内容，以下代码来自：百问网）：</p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;sys/types.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;sys/stat.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;fcntl.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;unistd.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdio.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;string.h></span></span>

<span class="token comment" spellcheck="true">/*
 * ./hello_drv_test -w abc
 * ./hello_drv_test -r
 */</span>
<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">int</span> argc<span class="token punctuation">,</span> <span class="token keyword">char</span> <span class="token operator">*</span><span class="token operator">*</span>argv<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">int</span> fd<span class="token punctuation">;</span>
    <span class="token keyword">char</span> buf<span class="token punctuation">[</span><span class="token number">1024</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> len<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/* 1. 判断参数 */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>argc <span class="token operator">&lt;</span> <span class="token number">2</span><span class="token punctuation">)</span> 
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"Usage: %s -w &lt;string>\n"</span><span class="token punctuation">,</span> argv<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"       %s -r\n"</span><span class="token punctuation">,</span> argv<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 2. 打开文件 */</span>
    fd <span class="token operator">=</span> <span class="token function">open</span><span class="token punctuation">(</span><span class="token string">"/dev/hello"</span><span class="token punctuation">,</span> O_RDWR<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>fd <span class="token operator">==</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"can not open file /dev/hello\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 3. 写文件或读文件 */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token number">0</span> <span class="token operator">==</span> <span class="token function">strcmp</span><span class="token punctuation">(</span>argv<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token string">"-w"</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token punctuation">(</span>argc <span class="token operator">==</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        len <span class="token operator">=</span> <span class="token function">strlen</span><span class="token punctuation">(</span>argv<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
        len <span class="token operator">=</span> len <span class="token operator">&lt;</span> <span class="token number">1024</span> <span class="token operator">?</span> len <span class="token punctuation">:</span> <span class="token number">1024</span><span class="token punctuation">;</span>
        <span class="token function">write</span><span class="token punctuation">(</span>fd<span class="token punctuation">,</span> argv<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">,</span> len<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">else</span>
    <span class="token punctuation">{</span>
        len <span class="token operator">=</span> <span class="token function">read</span><span class="token punctuation">(</span>fd<span class="token punctuation">,</span> buf<span class="token punctuation">,</span> <span class="token number">1024</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        
        buf<span class="token punctuation">[</span><span class="token number">1023</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token string">'\0'</span><span class="token punctuation">;</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"APP read : %s\n"</span><span class="token punctuation">,</span> buf<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token function">close</span><span class="token punctuation">(</span>fd<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>就是一些读写操作，跟我们学习文件操作是一样的。学单片机的有些朋友可能不太熟悉main函数的这种写法：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">int</span> argc<span class="token punctuation">,</span> <span class="token keyword">char</span> <span class="token operator">*</span><span class="token operator">*</span>argv<span class="token punctuation">)</span></code></pre>
<p>main函数在C中有好几种写法（可查看往期笔记：<a href="https://www.lizhengnian.cn/2018/10/02/c-yu-yan-bi-ji-main-han-shu-de-ji-chong-xing-shi/">main函数的几种写法</a>），在Linux中常用这种写法。argc与argv这两个值可以从终端（命令行）输入，因此这两个参数也被称为命令行参数。<code>argc</code>为命令行参数的个数，<code>argv</code>为字符串命令行参数的首地址。</p>
<p>最后，我们把编译生成的驱动模块<code>hello_drv.ko</code>与应用程序<code>hello_drv_test</code>放到共享目录录nfs_share中，同时在开发板终端挂载共享目录：</p>
<pre class=" language-c"><code class="language-c">mount <span class="token operator">-</span>t nfs <span class="token operator">-</span>o nolock<span class="token punctuation">,</span>vers<span class="token operator">=</span><span class="token number">4</span> <span class="token number">192.168</span><span class="token punctuation">.</span><span class="token number">1.104</span><span class="token punctuation">:</span><span class="token operator">/</span>home<span class="token operator">/</span>book<span class="token operator">/</span>nfs_share <span class="token operator">/</span>mnt</code></pre>
<p>关于ntf网络文件系统的使用可查看往期笔记：<a href="https://www.lizhengnian.cn/2020/03/01/linux-bi-ji-gua-zai-wang-luo-wen-jian-xi-tong/">【Linux笔记】网络文件系统</a>。</p>
<p>然后我们通过<code>insmod</code> 命令装载驱动，但是出现了如下错误：</p>
<p><img src="https://s1.ax1x.com/2020/03/15/83bk34.png" alt="83bk34.png"></p>
<p>这是因为我们的驱动的编译依赖与内核版本，编译用的内核版本与当前开发板运行的内核的版本不一致所以会产生该错误，重新编译内核，并把编译生成的Linux内核zImage映像文件与设备树文件*.dts文件拷贝到开发板根文件系统的/boot目录下，然后进行同步操作：</p>
<pre><code>#mount -t nfs -o nolock,vers=4 192.168.1.114:/home/book/nfs_share /mnt
#cp /mnt/zImage /boot
#cp /mnt/.dtb /boot
#sync</code></pre><p>最后，重启开发板。最后，成功运行程序：</p>
<p><img src="https://s1.ax1x.com/2020/03/15/83bAgJ.png" alt="83bAgJ.png"></p>
<p>下面是完整的hello驱动程序（来源：百问网）：</p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/module.h></span></span>

<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/fs.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/errno.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/miscdevice.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/kernel.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/major.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/mutex.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/proc_fs.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/seq_file.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/stat.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/init.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/device.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/tty.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/kmod.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;linux/gfp.h></span></span>

<span class="token comment" spellcheck="true">/* 1. 确定主设备号                                                                 */</span>
<span class="token keyword">static</span> <span class="token keyword">int</span> major <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">static</span> <span class="token keyword">char</span> kernel_buf<span class="token punctuation">[</span><span class="token number">1024</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token keyword">static</span> <span class="token keyword">struct</span> class <span class="token operator">*</span>hello_class<span class="token punctuation">;</span>


<span class="token macro property">#<span class="token directive keyword">define</span> MIN(a, b) (a &lt; b ? a : b)</span>

<span class="token comment" spellcheck="true">/* 3. 实现对应的open/read/write等函数，填入file_operations结构体                   */</span>
<span class="token keyword">static</span> ssize_t <span class="token function">hello_drv_read</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> file <span class="token operator">*</span>file<span class="token punctuation">,</span> <span class="token keyword">char</span> __user <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t size<span class="token punctuation">,</span> loff_t <span class="token operator">*</span>offset<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">int</span> err<span class="token punctuation">;</span>
    <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    err <span class="token operator">=</span> <span class="token function">copy_to_user</span><span class="token punctuation">(</span>buf<span class="token punctuation">,</span> kernel_buf<span class="token punctuation">,</span> <span class="token function">MIN</span><span class="token punctuation">(</span><span class="token number">1024</span><span class="token punctuation">,</span> size<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token function">MIN</span><span class="token punctuation">(</span><span class="token number">1024</span><span class="token punctuation">,</span> size<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">static</span> ssize_t <span class="token function">hello_drv_write</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> file <span class="token operator">*</span>file<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token keyword">char</span> __user <span class="token operator">*</span>buf<span class="token punctuation">,</span> size_t size<span class="token punctuation">,</span> loff_t <span class="token operator">*</span>offset<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">int</span> err<span class="token punctuation">;</span>
    <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    err <span class="token operator">=</span> <span class="token function">copy_from_user</span><span class="token punctuation">(</span>kernel_buf<span class="token punctuation">,</span> buf<span class="token punctuation">,</span> <span class="token function">MIN</span><span class="token punctuation">(</span><span class="token number">1024</span><span class="token punctuation">,</span> size<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token function">MIN</span><span class="token punctuation">(</span><span class="token number">1024</span><span class="token punctuation">,</span> size<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">static</span> <span class="token keyword">int</span> <span class="token function">hello_drv_open</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> inode <span class="token operator">*</span>node<span class="token punctuation">,</span> <span class="token keyword">struct</span> file <span class="token operator">*</span>file<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">static</span> <span class="token keyword">int</span> <span class="token function">hello_drv_close</span> <span class="token punctuation">(</span><span class="token keyword">struct</span> inode <span class="token operator">*</span>node<span class="token punctuation">,</span> <span class="token keyword">struct</span> file <span class="token operator">*</span>file<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">/* 2. 定义自己的file_operations结构体                                              */</span>
<span class="token keyword">static</span> <span class="token keyword">struct</span> file_operations hello_drv <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token punctuation">.</span>owner     <span class="token operator">=</span> THIS_MODULE<span class="token punctuation">,</span>
    <span class="token punctuation">.</span>open    <span class="token operator">=</span> hello_drv_open<span class="token punctuation">,</span>
    <span class="token punctuation">.</span>read    <span class="token operator">=</span> hello_drv_read<span class="token punctuation">,</span>
    <span class="token punctuation">.</span>write   <span class="token operator">=</span> hello_drv_write<span class="token punctuation">,</span>
    <span class="token punctuation">.</span>release <span class="token operator">=</span> hello_drv_close<span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">/* 4. 把file_operations结构体告诉内核：注册驱动程序                                */</span>
<span class="token comment" spellcheck="true">/* 5. 谁来注册驱动程序啊？得有一个入口函数：安装驱动程序时，就会去调用这个入口函数 */</span>
<span class="token keyword">static</span> <span class="token keyword">int</span> __init <span class="token function">hello_init</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">int</span> err<span class="token punctuation">;</span>

    <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    major <span class="token operator">=</span> <span class="token function">register_chrdev</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token string">"hello"</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>hello_drv<span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">/* /dev/hello */</span>


    hello_class <span class="token operator">=</span> <span class="token function">class_create</span><span class="token punctuation">(</span>THIS_MODULE<span class="token punctuation">,</span> <span class="token string">"hello_class"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    err <span class="token operator">=</span> <span class="token function">PTR_ERR</span><span class="token punctuation">(</span>hello_class<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">IS_ERR</span><span class="token punctuation">(</span>hello_class<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">unregister_chrdev</span><span class="token punctuation">(</span>major<span class="token punctuation">,</span> <span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token function">device_create</span><span class="token punctuation">(</span>hello_class<span class="token punctuation">,</span> <span class="token constant">NULL</span><span class="token punctuation">,</span> <span class="token function">MKDEV</span><span class="token punctuation">(</span>major<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token constant">NULL</span><span class="token punctuation">,</span> <span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">/* /dev/hello */</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">/* 6. 有入口函数就应该有出口函数：卸载驱动程序时，就会去调用这个出口函数           */</span>
<span class="token keyword">static</span> <span class="token keyword">void</span> __exit <span class="token function">hello_exit</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token function">printk</span><span class="token punctuation">(</span><span class="token string">"%s %s line %d\n"</span><span class="token punctuation">,</span> <span class="token constant">__FILE__</span><span class="token punctuation">,</span> __FUNCTION__<span class="token punctuation">,</span> <span class="token constant">__LINE__</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">device_destroy</span><span class="token punctuation">(</span>hello_class<span class="token punctuation">,</span> <span class="token function">MKDEV</span><span class="token punctuation">(</span>major<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">class_destroy</span><span class="token punctuation">(</span>hello_class<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">unregister_chrdev</span><span class="token punctuation">(</span>major<span class="token punctuation">,</span> <span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>


<span class="token comment" spellcheck="true">/* 7. 其他完善：提供设备信息，自动创建设备节点                                     */</span>

<span class="token function">module_init</span><span class="token punctuation">(</span>hello_init<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">module_exit</span><span class="token punctuation">(</span>hello_exit<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token function">MODULE_LICENSE</span><span class="token punctuation">(</span><span class="token string">"GPL"</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>嵌入式Linux的学习内容是很多的、坑也是很多的，死磕到底即可。</p>
<hr>
<p>我的个人博客：<a href="https://www.lizhengnian.cn/">https://www.lizhengnian.cn/</a></p>
<p>我的微信公众号：嵌入式大杂烩</p>
<p>我的CSDN博客：<a href="https://blog.csdn.net/zhengnianli" target="_blank" rel="noopener">https://blog.csdn.net/zhengnianli</a></p>
<p><img src="https://s2.ax1x.com/2019/06/11/VcSFJJ.md.png" alt></p>

            </div>
            <hr>

            
            <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.88rem;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-large waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fa fa-close"></i></a>
            <h4 class="reward-title">欢迎关注ZhengN的微信公众号</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <!--<ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微信公众号</a></li>
                    </ul>-->
					<!--
                    <div id="alipay">
                        <img src="" class="reward-img" alt="支付宝打赏二维码">
                    </div>
					-->
                    <div id="wechat">
                        <img src="/medias/reward/wechat.jpg" class="reward-img" alt="微信公众号二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            

            <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div>

<script src="/libs/share/js/social-share.min.js"></script>

            


        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments input[type=text],
    #vcomments input[type=email],
    #vcomments input[type=url],
    #vcomments textarea {
        box-sizing: border-box;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #42b983;
        font-weight: 500;
        text-decoration: underline;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div id="vcomments" class="card-content"></div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'Vc276uuqkd8y8heuqzShe9p1-gzGzoHsz',
        appKey: 'bUwy6lANpgeVdpcQamMtC8QD',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: '快来快活呀！^_^'
    });
</script>
    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2020/03/12/linux-led-qu-dong/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/5.jpg" class="responsive-img" alt="【Linux】LED驱动">
                        
                        <span class="card-title">【Linux】LED驱动</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            前言上一篇我们分享了字符设备驱动框架：嵌入式Linux驱动基础，当时分享的是hello驱动程序。学STM32我们从点灯开始，学Linux驱动我们自然也要点个灯来玩玩，尽量在从这些基础例程中榨取知识，细抠、细抠，为之后更复杂的知识打好基础。

                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="fa fa-clock-o fa-fw icon-date"></i>2020-03-12
                        </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Linux/" class="post-category" target="_blank">
                                    Linux
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Linux/" target="_blank">
                        <span class="chip bg-color">Linux</span>
                    </a>
                    
                    <a href="/tags/驱动/" target="_blank">
                        <span class="chip bg-color">驱动</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fa fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/03/12/jing-yan-pian-cong-dan-pian-ji-gong-cheng-shi-de-jiao-du-kan-qian-ru-shi-linux/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/14.jpg" class="responsive-img" alt="【经验篇】从单片机工程师的角度看嵌入式Linux">
                        
                        <span class="card-title">【经验篇】从单片机工程师的角度看嵌入式Linux</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            前言这篇文章简单我们来一起梳理嵌入式Linux的一些知识，方便于一些想跟我一样想要由单片机进阶到嵌入式Linux的朋友做一些参考学习。
嵌入式Linux学哪些东西1、认识Linux
学单片机的朋友有些有一些Linux基础了，但也不乏有些朋友
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2020-03-12
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/嵌入式/" class="post-category" target="_blank">
                                    嵌入式
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Linux/" target="_blank">
                        <span class="chip bg-color">Linux</span>
                    </a>
                    
                    <a href="/tags/单片机/" target="_blank">
                        <span class="chip bg-color">单片机</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>



    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fa fa-list"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).slideUp(500);
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).slideDown(500);
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>
    

</main>


<footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            本站由&copy;<a href="https://zhengnianli.github.io/" target="_blank">ZhengNian</a>基于
            <a href="https://hexo.io/" target="_blank">Hexo</a> 的
            <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">hexo-theme-matery</a>主题搭建.

            
                &nbsp;<i class="fa fa-area-chart"></i>&nbsp;站点总字数:&nbsp;
                <span class="white-color">187.2k</span>
            

            
			
                <br>
                
                <span id="busuanzi_container_site_pv">
                    <i class="fa fa-heart-o"></i>
                    本站总访问量 <span id="busuanzi_value_site_pv" class="white-color"></span>
                </span>
                
                
                <span id="busuanzi_container_site_uv">
                    <i class="fa fa-users"></i>
                    次,&nbsp;访客数 <span id="busuanzi_value_site_uv" class="white-color"></span> 人.
                </span>
                
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/zhengnianli" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fa fa-github"></i>
    </a>



    <a href="mailto:2238184039@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fa fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2238184039" class="tooltipped" data-tooltip="QQ联系我: 2238184039" data-position="top" data-delay="50">
        <i class="fa fa-qq"></i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fa fa-rss"></i>
    </a>
</div>
    </div>
</footer>

<div class="progress-bar"></div>


<!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字" class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
<!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


<script src="/libs/materialize/materialize.min.js"></script>
<script src="/libs/masonry/masonry.pkgd.min.js"></script>
<script src="/libs/aos/aos.js"></script>
<script src="/libs/scrollprogress/scrollProgress.min.js"></script>
<script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
<script src="/js/matery.js"></script>

<!-- Global site tag (gtag.js) - Google Analytics -->



    <script src="/libs/others/clicklove.js"></script>


    <script async src="/libs/others/busuanzi.pure.mini.js"></script>


</body>
</html>